package com.xinyu.filter;

import com.xinyu.config.JwtExcludedUrlsConfig;
import com.xinyu.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: JWTFilter
 * @Description: JWTFilter权限过滤器
 * @author: XinYu
 * @date: 2025/2/17
 * @since: (jdk_1.8)
 */
@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private JwtExcludedUrlsConfig jwtExcludedUrlsConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        // 获取放行的 URL 列表
        List<String> excludedUrls = jwtExcludedUrlsConfig.getUrls();

        // 检查当前 URL 是否需要放行
        for (String excludedUrl : excludedUrls) {
            if (url.contains(excludedUrl)) {
                System.out.println("无需登录，直接放行");
                filterChain.doFilter(request, response);
                return;
            }
        }

        String token = request.getHeader("Authorization");

        if (token != null) {
            if (JWTUtils.validateToken(token)) {
                // 获取 username 和 userId
                String username = JWTUtils.getUsernameFromToken(token);
                Integer userId = JWTUtils.getUserIdFromToken(token);

                // 创建 Authentication 对象并存入 SecurityContext
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, null // 这里可以设置权限信息，如果需要
                );
                authentication.setDetails(userId); // 设置 userId 作为额外的细节，方便后续获取

                // 设置 Spring Security 上下文
                SecurityContext securityContext = SecurityContextHolder.getContext();
                securityContext.setAuthentication(authentication);

                System.out.println("Token验证成功，username: " + username + ", userId: " + userId);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token无效或过期");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未提供Token");
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁逻辑
    }
}
